package com.dyna.core.validator;

import com.dyna.core.aop.annotation.EnumValid;
import com.dyna.core.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 枚举校验
 */
@Slf4j
@Component
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {

    // 存具体枚举的值
    private final List<Object> values = new ArrayList<>();

    @Override
    public void initialize(EnumValid constraintAnnotation) {

        Class<?> enumClazz = constraintAnnotation.value();
        Object[] enumConstants = enumClazz.getEnumConstants();
        if (null == enumConstants) {
            return;
        }
        Method method = BeanUtils.findMethod(enumClazz, constraintAnnotation.method());
        if (null == method) {
            log.warn("枚举对象:[{}]中不存在方法:[{}],请检查.", enumClazz.getName(), constraintAnnotation.method());
            throw new CustomException("枚举对象中不存在获取值的方法");
        }

        method.setAccessible(true);
        try {
            for (Object enumConstant : enumConstants) {
                values.add(method.invoke(enumConstant));
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.warn("获取枚举类:[{}]的枚举对象的值失败.", enumClazz);
            throw new CustomException("获取枚举值失败");
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return null == value || values.contains(value);
    }
}